// express全局中间件

const express = require('express');
const path = require("path");
const {appendFileSync} = require("fs");
const app = express();

// // http://localhost:9017/home
// app.get('/home', (req, res) => {
//     let {url, ip} = req
//     appendFileSync(path.resolve(__dirname, './access.log'), `${url} ${ip}\n`)
//     res.send('hello home')
// })
//
// // http://localhost:9017/admin
// app.get('/admin', (req, res) => {
//     let {url, ip} = req
//     appendFileSync(path.resolve(__dirname, './access.log'), `${url} ${ip}\n`)
//     res.send('hello admin')
// })

// 声明中间件函数
function recordMiddleware(req, res, next){
    let {url, ip} = req
    appendFileSync(path.resolve(__dirname, './access.log'), `${url} ${ip}\n`)
    next()
}

// 使用中间件函数
app.use(recordMiddleware)

// http://localhost:9017/home
app.get('/home', (req, res) => {
    res.send('hello home')
})

// http://localhost:9017/admin
app.get('/admin', (req, res) => {
    res.send('hello admin')
})

app.all('*', (req, res) => {
    res.end('404 Not Found')
})

app.listen(9017, () => {
    console.log('express server running at http://127.0.0.1:9017')
})